﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Controllers;
using Common.Logging;
using In.Api.Dto.HisWs;
using Newtonsoft.Json;
using OutDbContext;
using User.Api.BizExtensions;
using User.Api.Dto.Doctor;
using User.Api.HttpClients;

namespace User.Api.Controllers
{
    public class DoctorController : ApiController
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(DoctorController));
        private HzfyWeiXinEntities _ctx;

        protected override void Initialize(HttpControllerContext controllerContext)
        {
            _ctx = new HzfyWeiXinEntities();
            base.Initialize(controllerContext);
        }

        protected override void Dispose(bool disposing)
        {
            _ctx.Dispose();
            base.Dispose(disposing);
        }

        /// <summary>
        /// 获取医生信息，含医生的排班信息
        /// </summary>
        /// <param name="deptId">科室的院内编码</param>
        /// <param name="doctorId">医生的院内编码</param>
        /// <param name="orderType">0:预约 2：当天</param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("GetByDoctorId")]
        public GetByDoctorIdResponse GetByDoctorId(string deptId, string doctorId)
        {
            var doctor = _ctx.Doctor.FirstOrDefault(x => x.DeptId == deptId && x.DoctorId == doctorId);

            if (doctor == null)
            {
                return new GetByDoctorIdResponse
                {
                    ResultCode = "1",
                    ResultMsg = "找不到医生"
                };
            }

            var res = new GetByDoctorIdResponse
            {
                DefaultSelectedDay = "无剩余号源",
                Today = DateTime.Now.ToString("yyyy-MM-dd"),
                RegDays = new List<GetByDoctorIdResponse.ScheduleDay>()
            };
            for (int i = 0; i < 8; i++)
            {
                res.RegDays.Add(new GetByDoctorIdResponse.ScheduleDay
                {
                    Date = DateTime.Now.AddDays(i).ToString("yyyy-MM-dd"),
                    IsFull = true,
                    TimeSlices = new List<GetByDoctorIdResponse.TimeSlice>()
                });
            }
            //if (orderType == "2")
            //{
            //    //当天挂号限制
            //    #region (8点前不能挂号,12:00-14:30不能挂号)
            //    if (System.DateTime.Now.Hour < 8)
            //    {
            //        res.ResultCode = "1";
            //        res.ResultMsg = "很抱歉，现在还不是挂号时间，请您于8点后再挂号！";
            //        return res;
            //    }
            //    if (System.DateTime.Now.Hour >= 12 && (String.Compare(DateTime.Now.ToString("HH:mm"), "14:30", StringComparison.Ordinal) < 0))
            //    {
            //        res.ResultCode = "1";
            //        res.ResultMsg = "很抱歉，现在还不是挂号时间，请您于14点30分后再挂号！";
            //        return res;
            //    }

            //    #endregion
            //}

            res.DeptId = deptId;
            res.DeptName = doctor.DepartName;
            res.DoctorId = doctorId;
            res.DoctorName = doctor.DoctorName;
            res.DoctorDesc = string.IsNullOrEmpty(doctor.Desc) ? "暂无介绍" : doctor.Desc;
            res.Sex = doctor.Gender;// DoctorExtensions.ToZhSex(doctor.Gender);
            res.Title = doctor.Title;

            //获取排班
            var request = new Request4GetScheduleInfo
            {
                DeptId = deptId,
                DoctorId = doctorId,
                BeginDate = DateTime.Now.ToString("yyyy-MM-dd"),
                EndDate = DateTime.Now.AddDays(7).ToString("yyyy-MM-dd")
            };

            Response4GetScheduleInfo response;
            try
            {
                var httpClient = InHttpClient.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync("HisNewWs/GetScheduleInfo", request).Result;
                responseMsg.EnsureSuccessStatusCode();
                response = responseMsg.Content.ReadAsAsync<Response4GetScheduleInfo>().Result;
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("调用院内排班Api出错,信息：{0}", JsonConvert.SerializeObject(ex));
                res.ResultCode = "1";
                res.ResultMsg = "获取排班超时";
                return res;
            }

            if (response.ResultCode != "0")
            {
                res.ResultCode = "2";
                res.ResultMsg = response.ResultDesc;
                return res;
            }

            var scheduleInfos = response.ScheduleList;

            foreach (var scheduleInfo in scheduleInfos)
            {
                //已停诊和已经结束的排班不显示
                if (scheduleInfo.IsHalt == "0" &&
                    (String.CompareOrdinal(scheduleInfo.RegDate, DateTime.Now.ToString("yyyy-MM-dd")) > 0
                     ||
                     (String.CompareOrdinal(scheduleInfo.RegDate, DateTime.Now.ToString("yyyy-MM-dd")) == 0
                      && String.CompareOrdinal(scheduleInfo.EndTime, DateTime.Now.ToString("HH:mm")) > 0)))
                {
                    //挂号提前30分钟放号
                    if (String.CompareOrdinal(scheduleInfo.RegDate, DateTime.Now.ToString("yyyy-MM-dd")) == 0
                        &&
                        (String.CompareOrdinal(scheduleInfo.StartTime, DateTime.Now.AddMinutes(30).ToString("HH:mm")) >
                         0 //未到时间                                                                        
                         || String.CompareOrdinal(scheduleInfo.EndTime, DateTime.Now.ToString("HH:mm")) < 0 //已过时间 
                            )
                        )
                    {
                        continue;
                    }

                    var scheduleDay = res.RegDays.First(x => x.Date == scheduleInfo.RegDate);
                    if (scheduleInfo.TotalCount == "不限号" || scheduleInfo.LeaveCount.ToInt32OrDefault() > 0)
                    {
                        scheduleDay.IsFull = false;
                        if (res.DefaultSelectedDay == "无剩余号源")
                        {
                            res.DefaultSelectedDay = scheduleInfo.RegDate;
                        }
                    }

                    scheduleDay.TimeSlices.Add(new GetByDoctorIdResponse.TimeSlice
                    {
                        DeptId = scheduleInfo.DeptId,
                        DeptName = scheduleInfo.DeptName,
                        DoctorId = scheduleInfo.DoctorId,
                        DoctorName = scheduleInfo.DoctorName,
                        Title = scheduleInfo.Title,
                        IsHalt = scheduleInfo.IsHalt,
                        RegType = scheduleInfo.RegType,
                        SliceName = scheduleInfo.TimeSlice,
                        SliceStartTime = scheduleInfo.StartTime,
                        SliceEndTime = scheduleInfo.EndTime,
                        LeaveCount =
                            scheduleInfo.LeaveCount.ToInt32OrDefault() < 0
                                ? 0
                                : scheduleInfo.LeaveCount.ToInt32OrDefault(),
                        TotalCount = scheduleInfo.TotalCount.ToInt32OrDefault(),
                        HasTimePoint = scheduleInfo.IsTimeFlag == "1",
                        RegFee = scheduleInfo.RegDate.ToDecimalOrDefault(),
                        TreatFee = scheduleInfo.TreatFee.ToDecimalOrDefault(),
                        OtherFee = scheduleInfo.OtherFee.ToDecimalOrDefault(),
                        TotalFee =
                            scheduleInfo.RegDate.ToDecimalOrDefault() + scheduleInfo.TreatFee.ToDecimalOrDefault() +
                            scheduleInfo.OtherFee.ToDecimalOrDefault()
                    });

                }
            }
            res.ResultCode = "0";
            res.ResultMsg = "";
            return res;
        }



        /// <summary>
        ///  获取排班分时信息
        /// </summary>
        /// <param name="deptId">科室的院内编号</param>
        /// <param name="doctorId">医生的院内编号</param>
        /// <param name="regDate">挂号日期</param>
        /// <param name="regType">号源类型</param>
        /// <param name="timeSlice">时段</param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("GetScheduleTimePoints")]
        public GetScheduleTimePointsResponse GetScheduleTimePoints(string deptId, string doctorId, string regDate,
            string regType, string timeSlice)
        {
            var res = new GetScheduleTimePointsResponse();
            res.TimePoints = new List<GetScheduleTimePointsResponse.TimePoint>();

            //执行获取排班分时信息
            var request = new Request4GetTimeRegInfo();
            request.HospitalId = "2394";
            request.DeptId = deptId;
            request.DoctorId = doctorId;
            request.RegDate = regDate;
            request.TimeSlice = timeSlice;

            Response4GetTimeRegInfo response;
            try
            {
                var httpClient = InHttpClient.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync("HisNewWs/GetTimeRegInfo", request).Result;
                responseMsg.EnsureSuccessStatusCode();
                response = responseMsg.Content.ReadAsAsync<Response4GetTimeRegInfo>().Result;
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("调用院内排班分时Api出错,信息：{0}", JsonConvert.SerializeObject(ex));
                res.ResultCode = "1";
                res.ResultMsg = "获取排班分时信息超时";
                return res;
            }

            if (response.ResultCode != "0")
            {
                res.ResultCode = "2";
                res.ResultMsg = response.ResultDesc;
                return res;
            }

            res.ResultCode = "0";
            res.ResultMsg = "";
            res.TimePoints = response.TimeRegList.Select(x => new GetScheduleTimePointsResponse.TimePoint
            {
                StartTime = x.StartTime,
                EndTime = x.EndTime,
                TotalCount = x.TotalCount,
                LeaveCount = x.LeaveCount,
                SqNo = x.SqNo,
                czDeptCode = x.czDeptCode
            }).ToList();

            return res;
        }


        public class RegScheduleInfoComparer : IComparer<Response4GetScheduleInfoSubScheduleInfo>
        {
            public int Compare(Response4GetScheduleInfoSubScheduleInfo x, Response4GetScheduleInfoSubScheduleInfo y)
            {
                //var rtn = String.Compare(x.StartTime, y.StartTime, StringComparison.Ordinal);
                //if (rtn == 0)
                //{                
                //    var titles = new[] { "主任医师", "副主任医师", "主治医师", "医师" };

                //    rtn = titles.IndexOf(x.Title).CompareTo(titles.IndexOf(y.Title));
                //}
                var times = new[] { "下午", "上午", "全天" };
                var rtn = times.IndexOf(y.TimeSlice).CompareTo(times.IndexOf(x.TimeSlice));

                return rtn;
            }
        }
 
    }
}
